<template>
  <div v-show="isShow" class="video-container">
    <!-- 被呼叫布局 & 语音通话布局 -->
    <div v-show="beCalling || !isVideo" class="becalling-wrapper">
      <div class="user-info">
        <img class="avatar" :src="avatarImg" />
        <span class="name">{{ doctorName }}</span>
        <p v-show="beCalling">邀请你视频通话…</p>
      </div>
      <p v-if="!beCalling" class="time">{{ netcallTime | transferTime }}</p>
      <!-- 按钮区域 -->
      <div v-if="beCalling" class="becalling-btn">
        <span class="refuse" @click="handleRefuse">拒绝</span>
        <span class="agree" @click="handleAgree">接听</span>
      </div>
      <!-- <ul v-else class="tab-bar">
        <li class="silence" :class="{isSilence}" @click="openOrCloseSilence">静音</li>
        <li class="over" @click="handleOver">取消</li>
        <li class="speaker" :class="{isSpeaker}" @click="openOrCloseSpeaker">免提</li>
      </ul> -->
    </div>
    <!-- 视频通话布局 -->
    <div v-show="!beCalling && isVideo" class="becalled-wrapper">
      <div class="content">
        <!--画面div-->
        <div id="video-large"></div>
        <!--小画面div-->
        <div id="video-small" class="sub-window">
          <!-- <img v-show="isWait" class="loading-img" />-->
        </div>
      </div>
      <p class="time" style="color: #fff">{{ netcallTime | transferTime }}</p>
      <!--按钮区域-->
      <ul class="tab-bar" :class="{ isVideo }">
        <!-- <li class="switch-audio" @click="switchAudioOrVideo">切换语音通话</li> -->
        <li class="over" @click="handleOver">挂机</li>
        <li class="switch-camera" @click="switchCamera">切换摄像头</li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import WebRTCCall from '@/utils/webIM/WebRTCCall';
import { initLocalStream } from '@/utils/webIM/WebRTCCall';
import Bus from '@/utils/bus';
import defDocAvatar from '@/assets/videoCall/icon-agree.png';

export default {
  props: {
    isShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      callTimer: null,
      netcallTime: 0, // 通话时长,
      defDocAvatar,
      localUid: 13783339953,
      channelName: 'doctor-85920015787888711',
      token: '72b8fcb95561dcde6316c92f755a6b626532ca9a'
    };
  },
  computed: {
    ...mapGetters({
      beCalling: 'videoCall/beCalling', // 被呼叫中
      isSilence: 'videoCall/isSilence', // 是否静音
      isSpeaker: 'videoCall/isSpeaker', // 是否开扬声器
      isWait: 'videoCall/isWait', // 是否等待对方进入房间
      isVideo: 'videoCall/isVideo', // 是否在视频通话中
      isSmallWindow: 'videoCall/isSmallWindow', // 是否是小窗口
      videoDevices: 'videoCall/videoDevices',
      videoDeviceId: 'videoCall/videoDeviceId'
    }),
    avatarImg() {
      return this.defDocAvatar;
    },
    doctorName() {
      return '11';
    }
  },
  watch: {
    isShow(newVal) {
      if (newVal) {
        !this.beCalling && this.isVideo && this.play();
      }
    }
  },
  mounted() {
    Bus.$on('hangUp', () => {
      this.handleOver();
    });
    Bus.$on('playRemoteStream', remoteStream => {
      this.$nextTick(() => {
        this.playRemoteStream(remoteStream);
      });
    });
    Bus.$on('playLocalStream', () => {
      this.$nextTick(() => {
        this.playLocalStream();
      });
    });
  },
  methods: {
    play() {
      this.$nextTick(() => {
        this.playLocalStream();
        this.playRemoteStream(WebRTCCall.remoteStream);
      });
    },
    // getToken() {
    //   const { thirdId, phone } = this.$store.state.nim.questionDetail || {};
    //   this.localUid = phone ? Number(`${phone}1`) : '';
    //   this.channelName = `doctor-${thirdId}`;
    //   this.$api
    //     .queryVideoImToken({
    //       channelCode: this.$constant.manniu_video_service_code,
    //       telphone: this.localUid,
    //       channelName: this.channelName
    //     })
    //     .then(res => {
    //       const { data } = res || {};
    //       if (data) {
    //         this.joinChannel(data);
    //       }
    //     });
    // },
    handleAgree() {
      this.$store.commit('videoCall/setBeCalling', false);
      this.$store.commit('videoCall/setVideo', true);
      // this.getToken();
      this.joinChannel(this.token);
    },
    handleRefuse() {
      console.log('handleRefuse====');
      this.$store.dispatch('nim/sendVCustomMsg', {
        params: { type: 'REFUSE_JOIN', text: '' },
        type: 'customVideo'
      });
      this.$store.commit('videoCall/setShowCall', false);
    },
    // 挂机
    handleOver() {
      console.log('handleOver===');
      try {
        WebRTCCall.localStream && WebRTCCall.localStream.destroy();
        WebRTCCall.client && WebRTCCall.client.leave();
        this.$store.commit('videoCall/resetCall');
        this.clearCallTime();
      } catch (e) {
        console.error('handleOver==', e);
      }
    },
    // 加入房间
    joinChannel() {
      if (!WebRTCCall.client) {
        this.$toast('内部错误，请重新加入房间');
        return;
      }
      WebRTCCall.client
        .join({
          token: this.token,
          channelName: this.channelName,
          uid: this.localUid
        })
        .then(data => {
          console.info('加入房间成功，开始初始化本地音视频流', data);
          this.callTimer = setInterval(() => {
            this.netcallTime++;
          }, 1000);
          initLocalStream(this.localUid);
        })
        .catch(error => {
          console.error('加入房间失败：', error);
          this.$toast(`${error}: 请检查appkey或者token是否正确`);
        });
    },
    playLocalStream() {
      if (WebRTCCall.localStream) {
        const div = document.getElementById('video-small');
        WebRTCCall.localStream
          .play(div)
          .then(() => {
            console.log('playLocalStream-播放视频');
            WebRTCCall.localStream.setLocalRenderMode({
              // 设置视频窗口大小
              width: div.clientWidth,
              height: div.clientHeight,
              cut: true // 是否裁剪
            });
          })
          .catch(() => {
            console.log('playLocalStream-播放视频失败');
          });
      }
    },
    playRemoteStream(remoteStream) {
      if (remoteStream) {
        const div = document.getElementById('video-large');
        remoteStream
          .play(div)
          .then(() => {
            console.log('playRemoteStream-播放视频');
            remoteStream.setRemoteRenderMode({
              // 设置视频窗口大小
              width: div.clientWidth,
              height: div.clientHeight,
              cut: false // 是否裁剪
            });
          })
          .catch(() => {
            console.log('playRemoteStream-播放视频失败');
          });
      }
    },
    // 静音开启或关闭
    openOrCloseSilence() {
      if (!WebRTCCall.localStream) {
        this.$toast(this.isSilence ? '当前不能打开mic' : '当前不能关闭mic');
        return;
      }
      if (!this.isSilence) {
        WebRTCCall.localStream
          .close({
            type: 'audio'
          })
          .then(() => {
            this.isSilence = true;
          })
          .catch(err => {
            console.log('关闭mic失败: ', err);
            this.$toast('关闭mic失败');
          });
      } else {
        WebRTCCall.localStream
          .open({
            type: 'audio'
          })
          .then(() => {
            this.isSilence = false;
          })
          .catch(err => {
            console.log('打开mic失败: ', err);
            this.$toast('打开mic失败');
          });
      }
    },
    // 切换语音或者视频
    switchAudioOrVideo() {
      this.isVideo = false;
      WebRTCCall.localStream && WebRTCCall.localStream.muteVideo();
      WebRTCCall.remoteStream && WebRTCCall.remoteStream.muteVideo();
    },
    // 切换摄像头
    switchCamera() {
      console.log('switchCamera=====');
      if (
        this.videoDeviceId &&
        (this.videoDevices.length <= 1 || this.videoDevices.length >= 3)
      ) {
        this.$toast(
          this.videoDevices.length >= 3
            ? '3个或3个以上摄像头不能切换'
            : '只有一个摄像头不能切换'
        );
        return;
      }
      if (WebRTCCall.localStream) {
        WebRTCCall.localStream.destroy();
      }
      initLocalStream(this.localUid);
    },
    // 清空计时器
    clearCallTime() {
      if (this.callTimer) {
        clearInterval(this.callTimer);
        this.callTimer = null;
        this.netcallTime = 0;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.video-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: 1000;
}
.becalling-wrapper {
  width: 100vw;
  height: 100vh;
  background-color: #f8fafd;
  position: relative;
  overflow: hidden;

  .user-info {
    margin-top: 105px;
    text-align: center;
    .avatar {
      width: 150px;
      height: 150px;
      border-radius: 50%;
      margin: 0 auto 12px;
      background-color: #3ad9b7;
    }
    .name {
      font-size: 22px;
      font-weight: bold;
      color: #333333;
      line-height: 30px;
    }
    p {
      font-size: 16px;
      color: #333333;
      line-height: 22px;
      margin-top: 10px;
    }
  }

  .becalling-btn {
    position: absolute;
    bottom: 60px;
    left: 0;
    width: 100%;
    display: flex;
    justify-content: center;
    color: #333333;
    .refuse {
      width: 72px;
      padding-top: 82px;
      display: inline-block;
      background: url('~@/assets/videoCall/icon-refuse.png') no-repeat;
      background-size: 72px 72px;
      text-align: center;
      margin-right: 90px;
    }
    .agree {
      width: 72px;
      padding-top: 82px;
      display: inline-block;
      background: url('~@/assets/videoCall/icon-agree.png') no-repeat;
      background-size: 72px 72px;
      text-align: center;
    }
  }
}
.becalled-wrapper {
  width: 100vw;
  height: 100vh;
  background-image: linear-gradient(179deg, #141417 0%, #181824 100%);
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .content {
    flex: 1;
    position: relative;

    #video-large {
      width: 375px;
      height: 100%;
      background: #25252d;

      div {
        width: 375px;
        height: 100%;
      }
    }

    .sub-window {
      background: #f8fafd;
      position: absolute;
      z-index: 9;
      right: 0;
      top: 54px;
      width: 91px;
      height: 160px;

      .loading-img {
        display: block;
        width: 100%;
        height: 100%;
        background-color: #f8fafd;
      }
    }
  }
}
.time {
  position: absolute;
  bottom: 190px;
  left: 0;
  width: 100%;
  text-align: center;
  color: #333333;
  font-weight: bold;
}
.tab-bar {
  position: absolute;
  left: 0;
  bottom: 60px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-around;
  font-size: 15px;
  color: #333333;

  &.isVideo {
    color: #fff;
  }

  li {
    min-width: 90px;
    cursor: pointer;
    //静音
    &.silence {
      padding-top: 76px;
      background: url('~@/assets/videoCall/icon-silence-close.png') no-repeat
        center top;
      background-size: 64px 64px;
      text-align: center;

      &.isSilence {
        //已经开启静音
        background: url('~@/assets/videoCall/icon-silence-open.png') no-repeat
          center top;
        background-size: 64px 64px;
      }
    }

    &.over {
      padding-top: 80px;
      background: url('~@/assets/videoCall/icon-refuse.png') no-repeat center
        top;
      background-size: 72px 72px;
      text-align: center;
    }

    &.switch-camera {
      padding-top: 76px;
      background: url('~@/assets/videoCall/icon-camera.png') no-repeat center
        top;
      background-size: 64px 64px;
      text-align: center;
    }

    &.switch-audio {
      padding-top: 76px;
      background: url('~@/assets/videoCall/icon-audio.png') no-repeat center top;
      background-size: 64px 64px;
      text-align: center;
    }
    &.speaker {
      padding-top: 76px;
      background: url('~@/assets/videoCall/icon-loud-close.png') no-repeat
        center top;
      background-size: 64px 64px;
      text-align: center;
      &.isSpeaker {
        background: url('~@/assets/videoCall/icon-loud-open.png') no-repeat
          center top;
        background-size: 64px 64px;
      }
    }
  }
}
</style>
